<template>

    <mi-form-page @submit="submit" v-loading="edit.loading">
        <el-tree-v2 ref="treeRef"
                    :props="{value:'id',label:'title'}"
                    show-checkbox
                    :height="500" />
    </mi-form-page>
</template>

<script setup lang="ts">
import {ref, inject, reactive, onMounted, nextTick} from "vue";
import {simpleGet, simplePost} from "@/utils/request";
import {makeModelAuth} from "@/utils/auth";
import {ElTreeV2, FormInstance} from "element-plus";
import Edit from "@/model/edit";
import {msgSuccess} from "@/utils/alert";

const list = inject("list") as any
const edit = inject("editRules", new Edit({}))
const row:any = list?.currentRow
const id = row ? row.id: ''
const auth = makeModelAuth("auth.adminGroup")
const treeRef = ref<InstanceType<typeof ElTreeV2>>()

const submit = () => {
    edit.loading = true
    let checked = [...treeRef.value!.getCheckedKeys(), ...treeRef.value!.getHalfCheckedKeys()]
    simplePost("/auth.adminGroup/rule", {
        group_id:id,
        rules: checked,
    }).then((res:any) => {
        msgSuccess("保存成功")
        edit.show = false
    }).finally(() => {
        edit.loading = false
    })
}

onMounted(() => {
    edit.init(async () => {
        let {trees, checked} = await simpleGet('/auth.adminGroup/rule', {group_id:id})
        treeRef.value!.setData(trees)
        nextTick().then(r => {
            checked.forEach((key:any) => {
                key = Number(key)
                const node  = treeRef.value!.getNode(key)
                if (node?.isLeaf){
                    treeRef.value!.setChecked(key, true)
                }
            })
        })
    })
})

</script>

<style scoped>

</style>
